const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
const hangupButton = document.getElementById('hangupButton');
const userIdDisplay = document.getElementById('userId');

let localStream;
let remoteStream;
let pc1;
let pc2;
let userId;
let connections = new Map(); // 存储所有连接

// 添加在线用户管理
let onlineUsers = new Map();
const userList = document.getElementById('userList');

const configuration = {
    iceServers: [
        {
            urls: [
                'stun:stun.l.google.com:19302',
                'stun:stun1.l.google.com:19302'
            ]
        }
    ],
    iceTransportPolicy: 'all',
    bundlePolicy: 'max-bundle',
    rtcpMuxPolicy: 'require',
    iceCandidatePoolSize: 0
};

// 添加 WebSocket 连接
let ws;
const wsUrl = `ws://${window.location.hostname}:8080/signaling`;

// 添加新的变量
let currentCallId = null;
let isInCall = false;
const remoteVideoLabel = document.getElementById('remoteVideoLabel');
const screenShareButton = document.getElementById('screenShareButton');
const micButton = document.getElementById('micButton');
const cameraButton = document.getElementById('cameraButton');
const chatInput = document.getElementById('chatInput');
const sendMessageButton = document.getElementById('sendMessageButton');
const chatMessages = document.getElementById('chatMessages');
const emojiButton = document.getElementById('emojiButton');
let emojiPicker = null;

let isScreenSharing = false;
let originalStream = null;

// 添加白板相关变量
const whiteboardContainer = document.getElementById('whiteboardContainer');
const whiteboardCanvas = document.getElementById('whiteboardCanvas');
const whiteboardControls = document.getElementById('whiteboardControls');
const penButton = document.getElementById('penButton');
const eraserButton = document.getElementById('eraserButton');
const colorPicker = document.getElementById('colorPicker');
const clearButton = document.getElementById('clearButton');

let isDrawing = false;
let isErasing = false;
let ctx = null;
let lastX = 0;
let lastY = 0;

// 修改白板相关变量
let currentLineWidth = 2;
let isFullscreen = false;

// 添加全屏按钮
const fullscreenButton = document.createElement('button');
fullscreenButton.className = 'whiteboard-button';
fullscreenButton.title = '全屏';
fullscreenButton.innerHTML = '<i class="fas fa-expand"></i>';
whiteboardControls.appendChild(fullscreenButton);

// 添加线条粗细控制
const lineWidthControl = document.createElement('input');
lineWidthControl.type = 'range';
lineWidthControl.min = '1';
lineWidthControl.max = '20';
lineWidthControl.value = '2';
lineWidthControl.className = 'line-width-control';
lineWidthControl.title = '线条粗细';
whiteboardControls.insertBefore(lineWidthControl, colorPicker);

function connectWebSocket() {
    console.log('正在连接 WebSocket:', wsUrl);
    ws = new WebSocket(wsUrl);

    ws.onopen = () => {
        console.log('WebSocket 连接已建立');
        // 发送加入消息
        sendMessage({
            type: 'join',
            from: userId,
            name: `User-${userId}`
        });
    };

    ws.onmessage = (event) => {
        console.log('收到 WebSocket 消息:', event.data);
        const message = JSON.parse(event.data);
        handleSignalingMessage(message);
    };

    ws.onclose = () => {
        console.log('WebSocket 连接已关闭，3秒后重试');
        setTimeout(connectWebSocket, 3000);
    };

    ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
    };
}

function sendMessage(message) {
    if (ws && ws.readyState === WebSocket.OPEN) {
        console.log('发送消息:', message);
        ws.send(JSON.stringify(message));
    } else {
        console.warn('WebSocket 未连接，无法发送消息');
    }
}

function handleSignalingMessage(message) {
    console.log('收到信令消息:', message);
    switch (message.type) {
        case 'users':
            console.log('更新在线用户列表:', message.data);
            updateOnlineUsers(message.data);
            break;
        case 'call-invitation':
            console.log('收到通话邀请 from:', message.from);
            showCallDialog(message.from, message.name);
            break;
        case 'call-accepted':
            call(); // 当对方接受通话时，发起WebRTC连接
            break;
        case 'call-rejected':
            handleCallRejected(message.from);
            break;
        case 'offer':
            handleOffer(message.from, message.data);
            break;
        case 'answer':
            handleAnswer(message.from, message.data);
            break;
        case 'ice':
            handleIceCandidate(message.from, message.data);
            break;
        case 'call-ended':
            handleCallEnded(message.from);
            break;
        case 'chat':
            console.log('收到聊天消息:', message);
            if (message.from === currentCallId) {  // 只显示当前通话对象的消息
                addMessageToChat(message.data, false);
            }
            break;
        case 'whiteboard':
            handleWhiteboardMessage(message);
            break;
    }
}

function updateOnlineUsers(users) {
    // 清空现有用户列表
    userList.innerHTML = '';
    
    // 添加新的用户
    Object.entries(users).forEach(([id, name]) => {
        if (id !== userId) {
            addOnlineUser(id, name);
        }
    });
}

// 生成随机ID
function generateUserId() {
    return Math.floor(Math.random() * 9000 + 1000).toString();
}

// 修改 addOnlineUser 函数
function addOnlineUser(id, name) {
    if (id === userId) return; // 不显示自己
    
    const userItem = document.createElement('li');
    userItem.className = 'user-item';
    userItem.innerHTML = `
        <div class="user-info">
            <span>${name || 'User-' + id}</span>
        </div>
        <button class="call-button" data-user-id="${id}" ${isInCall ? 'disabled' : ''}>
            <i class="fas fa-video"></i>
        </button>
    `;

    const callButton = userItem.querySelector('.call-button');
    callButton.addEventListener('click', () => {
        if (!isInCall) {
            sendCallInvitation(id);
        }
    });

    // 检查是否需要立即更新状态
    if (id === currentCallId || isInCall) {
        updateUserStatus(id, id === currentCallId);
    }

    userList.appendChild(userItem);
    onlineUsers.set(id, userItem);
}

function removeOnlineUser(id) {
    const userItem = onlineUsers.get(id);
    if (userItem) {
        userItem.remove();
        onlineUsers.delete(id);
    }
}

// 修改 updateUserStatus 函数
function updateUserStatus(userId, isBusy) {
    const userItem = onlineUsers.get(userId);
    if (userItem) {
        const callButton = userItem.querySelector('.call-button');
        if (isBusy) {
            // 通话中 - 红色 + 呼吸灯效果
            callButton.classList.add('busy');
            callButton.disabled = true;
            // 添加通话提示
            if (userId === currentCallId) {
                callButton.setAttribute('data-tooltip', `正在与 User-${userId} 通话中`);
            }
        } else {
            // 可以通话 - 蓝色
            callButton.classList.remove('busy');
            callButton.disabled = isInCall;
            callButton.removeAttribute('data-tooltip');
        }
    }
}

// 修改 sendCallInvitation 函数
function sendCallInvitation(targetId) {
    console.log('发送通话邀请给:', targetId);
    sendMessage({
        type: 'call-invitation',
        from: userId,
        to: targetId,
        name: `User-${userId}`
    });
    currentCallId = targetId;
    isInCall = true;
    updateCallButtons();
    // 更新自己和对方的状态
    updateUserStatus(targetId, true);
    onlineUsers.forEach((userItem, userId) => {
        if (userId !== targetId) {
            const callButton = userItem.querySelector('.call-button');
            callButton.disabled = true;
            callButton.classList.remove('busy');
        }
    });
    hangupButton.classList.add('active');
}

// 显示通话邀请对话框
function showCallDialog(callerId, callerName) {
    const template = document.getElementById('call-dialog-template');
    const dialog = template.content.cloneNode(true);
    
    dialog.querySelector('.caller-name').textContent = callerName;
    
    const acceptButton = dialog.querySelector('.accept-button');
    const rejectButton = dialog.querySelector('.reject-button');
    
    acceptButton.addEventListener('click', () => {
        document.querySelector('.dialog-overlay').remove();
        acceptCall(callerId);
    });
    
    rejectButton.addEventListener('click', () => {
        document.querySelector('.dialog-overlay').remove();
        rejectCall(callerId);
    });
    
    document.body.appendChild(dialog);
}

// 接受通话
async function acceptCall(callerId) {
    try {
        currentCallId = callerId;
        isInCall = true;
        updateCallButtons();
        // 更新自己和对方的状态
        updateUserStatus(callerId, true);
        onlineUsers.forEach((userItem, userId) => {
            if (userId !== callerId) {
                const callButton = userItem.querySelector('.call-button');
                callButton.disabled = true;
                callButton.classList.remove('busy');
            }
        });
        hangupButton.classList.add('active');
        
        sendMessage({
            type: 'call-accepted',
            from: userId,
            to: callerId
        });
    } catch (e) {
        console.error('接受通话失败:', e);
        alert('接受通话失败: ' + e.message);
    }
}

// 拒绝通话
function rejectCall(callerId) {
    sendMessage({
        type: 'call-rejected',
        from: userId,
        to: callerId
    });
}

// 更新通话按钮状态
function updateCallButtons() {
    const callButtons = document.querySelectorAll('.call-button');
    callButtons.forEach(button => {
        button.disabled = isInCall;
    });
}

// 处理通话被拒绝
function handleCallRejected(fromId) {
    if (fromId === currentCallId) {
        alert('对方拒绝了通话请求');
        resetCallState();
    }
}

// 修改 resetCallState 函数
function resetCallState() {
    if (currentCallId) {
        updateUserStatus(currentCallId, false);
    }
    currentCallId = null;
    isInCall = false;
    
    // 更新所有用户的通话按钮状态为蓝色（可通话状态）
    onlineUsers.forEach((userItem, userId) => {
        const callButton = userItem.querySelector('.call-button');
        callButton.disabled = false;
        callButton.classList.remove('busy');
    });
}

// 修改 hangup 函数
function hangup() {
    // 关闭所有连接
    for (let [id, connection] of connections) {
        connection.close();
        console.log(`关闭与 ${id} 的连接`);
    }
    connections.clear();
    
    remoteVideo.srcObject = null;
    remoteVideoLabel.style.display = 'none';  // 隐藏远程视频标签
    hangupButton.classList.remove('active');
    
    if (currentCallId) {
        updateUserStatus(currentCallId, false);
        sendMessage({
            type: 'call-ended',
            from: userId,
            to: currentCallId
        });
    }
    
    resetCallState();
    if (isScreenSharing) {
        stopScreenSharing();
    }
    // 清空聊天区域
    chatMessages.innerHTML = '';
}

// 修改初始化函数
async function init() {
    userId = generateUserId();
    userIdDisplay.textContent = `你的ID: ${userId}`;
    
    try {
        // 自动开启摄像头
        await start();
    } catch (e) {
        console.error('自动开启摄像头失败:', e);
    }
    
    connectWebSocket();
    setupEmojiPicker();
}

// 移除按钮事件监听
hangupButton.onclick = hangup;

// 初始化
init();

// 修改 start 函数
async function start() {
    try {
        // 检查浏览器是否支持 getUserMedia
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            console.log('mediaDevices:', !!navigator.mediaDevices);
            console.log('getUserMedia:', !!navigator.mediaDevices?.getUserMedia);
            throw new Error('浏览器不支持 getUserMedia API');
        }

        // 请求所有可用的媒体设备
        const devices = await navigator.mediaDevices.enumerateDevices();
        console.log('可用设备:', devices);

        const stream = await navigator.mediaDevices.getUserMedia({
            audio: true,
            video: true
        });
        console.log('获取到媒体流:', stream.getTracks());
        
        localVideo.srcObject = stream;
        localStream = stream;

        return stream;
    } catch (e) {
        console.error('获取媒体设备失败:', e);
        alert(`获取媒体设备失败: ${e.message}\n\n请确保：\n1. 允许浏览器访问摄像头和麦克风\n2. 设备上有可用的摄像头和麦克风`);
        throw e;
    }
}

// 修改 call 函数
async function call() {
    try {
        if (!currentCallId) {
            alert('请选择要呼叫的用户');
            return;
        }

        // 确保有本地媒体流
        if (!localStream) {
            await start();
        }

        hangupButton.classList.add('active');

        const peerConnection = new RTCPeerConnection(configuration);
        connections.set(currentCallId, peerConnection);

        // 设置事件处理器
        peerConnection.onconnectionstatechange = () => {
            console.log(`与 ${currentCallId} 的连接状态:`, peerConnection.connectionState);
        };

        peerConnection.oniceconnectionstatechange = () => {
            console.log(`与 ${currentCallId} 的ICE连接状态:`, peerConnection.iceConnectionState);
        };

        peerConnection.onicecandidate = async (event) => {
            if (event.candidate) {  // 移除 host 限制，允许所有候选者
                console.log('发送 ICE 候选者:', event.candidate);
                sendMessage({
                    type: 'ice',
                    from: userId,
                    to: currentCallId,
                    data: event.candidate
                });
            }
        };

        peerConnection.ontrack = (event) => {
            console.log('收到远程轨道:', event.streams[0]);
            if (remoteVideo.srcObject !== event.streams[0]) {
                remoteVideo.srcObject = event.streams[0];
                remoteStream = event.streams[0];
                // 显示远程视频标签
                remoteVideoLabel.textContent = `User-${currentCallId}`;
                remoteVideoLabel.style.display = 'block';
            }
        };

        // 添加本地流
        localStream.getTracks().forEach(track => {
            console.log('添加本地轨道到连接:', track.kind);
            peerConnection.addTrack(track, localStream);
        });

        const offer = await peerConnection.createOffer({
            offerToReceiveAudio: true,
            offerToReceiveVideo: true
        });
        console.log('创建的 offer:', offer);
        await peerConnection.setLocalDescription(offer);
        
        sendMessage({
            type: 'offer',
            from: userId,
            to: currentCallId,
            data: offer
        });
    } catch (e) {
        console.error('创建offer失败:', e);
        alert('创建offer失败: ' + e.message);
        resetCallState();
    }
}

// 修改 handleOffer 函数
async function handleOffer(fromId, offer) {
    try {
        // 确保有本地媒体流
        if (!localStream) {
            await start();
        }

        const peerConnection = new RTCPeerConnection(configuration);
        connections.set(fromId, peerConnection);

        peerConnection.ontrack = (event) => {
            console.log('收到远程轨道:', event.streams[0]);
            remoteVideo.srcObject = event.streams[0];
            remoteStream = event.streams[0];
            // 显示远程视频标签
            remoteVideoLabel.textContent = `User-${fromId}`;
            remoteVideoLabel.style.display = 'block';
        };

        peerConnection.onicecandidate = async (event) => {
            if (event.candidate) {  // 移除 host 限制
                console.log('发送 ICE 候选者:', event.candidate);
                sendMessage({
                    type: 'ice',
                    from: userId,
                    to: fromId,
                    data: event.candidate
                });
            }
        };

        // 添加本地流
        localStream.getTracks().forEach(track => {
            console.log('添加本地轨道到连接:', track.kind);
            peerConnection.addTrack(track, localStream);
        });

        console.log('设置远程描述:', offer);
        await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
        
        console.log('创建应答...');
        const answer = await peerConnection.createAnswer();
        console.log('创建的应答:', answer);
        
        await peerConnection.setLocalDescription(answer);

        sendMessage({
            type: 'answer',
            from: userId,
            to: fromId,
            data: answer
        });
    } catch (e) {
        console.error('处理offer失败:', e);
        alert('处理offer失败: ' + e.message);
    }
}

// 添加处理 answer 的函数
async function handleAnswer(fromId, answer) {
    try {
        const peerConnection = connections.get(fromId);
        if (peerConnection) {
            await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
        }
    } catch (e) {
        console.error('处理answer失败:', e);
    }
}

// 添加处理 ICE candidate 的函数
async function handleIceCandidate(fromId, candidate) {
    try {
        const peerConnection = connections.get(fromId);
        if (peerConnection) {
            await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
        }
    } catch (e) {
        console.error('处理ICE candidate失败:', e);
    }
}

// 修改 handleCallEnded 函数
function handleCallEnded(fromId) {
    if (fromId === currentCallId) {
        alert('对方结束了通话');
        updateUserStatus(fromId, false);
        hangup();
    }
}

// 添加屏幕共享功能
async function toggleScreenShare() {
    try {
        if (!isScreenSharing) {
            const screenStream = await navigator.mediaDevices.getDisplayMedia({
                video: true
            });
            
            originalStream = localStream;
            localStream = screenStream;
            
            // 替换视频轨道
            const videoTrack = screenStream.getVideoTracks()[0];
            const sender = connections.get(currentCallId)?.getSenders()
                .find(s => s.track?.kind === 'video');
            if (sender) {
                await sender.replaceTrack(videoTrack);
            }
            
            localVideo.srcObject = screenStream;
            screenShareButton.classList.add('active');
            isScreenSharing = true;

            // 显示白板控件
            whiteboardControls.classList.add('active');
            initWhiteboard();

            // 监听屏幕共享结束
            videoTrack.onended = async () => {
                await stopScreenSharing();
            };
        } else {
            await stopScreenSharing();
        }
    } catch (e) {
        console.error('切换屏幕共享失败:', e);
    }
}

async function stopScreenSharing() {
    if (originalStream) {
        localStream = originalStream;
        const videoTrack = originalStream.getVideoTracks()[0];
        const sender = connections.get(currentCallId)?.getSenders()
            .find(s => s.track?.kind === 'video');
        if (sender) {
            await sender.replaceTrack(videoTrack);
        }
        localVideo.srcObject = originalStream;
    }
    screenShareButton.classList.remove('active');
    isScreenSharing = false;
    
    // 隐藏白板控件
    whiteboardControls.classList.remove('active');
    // 清空白板
    if (ctx) {
        ctx.clearRect(0, 0, whiteboardCanvas.width, whiteboardCanvas.height);
    }
}

// 修改发送消息函数
function sendChatMessage() {
    const message = chatInput.value.trim();
    if (message && currentCallId) {
        console.log('准备发送聊天消息给:', currentCallId);
        
        const chatMessage = {
            type: 'chat',
            from: userId,
            to: currentCallId,
            data: message,  // 使用 data 字段，与其他消息格式保持一致
            timestamp: new Date().toISOString()
        };
        
        console.log('发送聊天消息:', chatMessage);
        
        try {
            sendMessage(chatMessage);  // 使用 sendMessage 函数发送
            addMessageToChat(message, true);
            chatInput.value = '';
        } catch (error) {
            console.error('发送消息失败:', error);
        }
    } else {
        console.warn('无法发送消息: 没有选择聊天对象或消息为空');
    }
}

// 修改 setupEmojiPicker 函数
function setupEmojiPicker() {
    let emojiMenu = null;
    
    emojiButton.addEventListener('click', () => {
        if (emojiMenu) {
            emojiMenu.remove();
            emojiMenu = null;
            return;
        }

        // 创建表情菜单
        emojiMenu = document.createElement('div');
        emojiMenu.className = 'emoji-menu';
        
        // 常用表情列表
        const commonEmojis = ['😀', '😂', '🤣', '😊', '😍', '🥰', '😘', '👍', '❤️', '🎉', 
                            '😅', '😆', '😉', '😋', '😎', '😍', '😘', '🥰', '😗', '😙'];
        
        commonEmojis.forEach(emoji => {
            const emojiSpan = document.createElement('span');
            emojiSpan.className = 'emoji-item';
            emojiSpan.textContent = emoji;
            emojiSpan.onclick = () => {
                const cursorPos = chatInput.selectionStart;
                const text = chatInput.value;
                chatInput.value = text.slice(0, cursorPos) + emoji + text.slice(cursorPos);
                chatInput.focus();
                emojiMenu.remove();
                emojiMenu = null;
            };
            emojiMenu.appendChild(emojiSpan);
        });

        // 设置菜单样式
        emojiMenu.style.position = 'absolute';
        emojiMenu.style.bottom = '100%';
        emojiMenu.style.left = '0';
        emojiMenu.style.marginBottom = '5px';
        
        document.querySelector('.chat-input-area').appendChild(emojiMenu);

        // 点击其他地方关闭菜单
        const closeHandler = (e) => {
            if (emojiMenu && !emojiMenu.contains(e.target) && e.target !== emojiButton) {
                emojiMenu.remove();
                emojiMenu = null;
                document.removeEventListener('click', closeHandler);
            }
        };
        
        setTimeout(() => {
            document.addEventListener('click', closeHandler);
        }, 0);
    });
}

// 修改 addMessageToChat 函数
function addMessageToChat(message, isSent) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isSent ? 'sent' : 'received'}`;
    
    // 转义 HTML 并保留换行
    const escapedMessage = message
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\n/g, '<br>');
    
    messageDiv.innerHTML = `
        <div class="sender">${isSent ? '我' : `User-${currentCallId}`}</div>
        <div class="content">${escapedMessage}</div>
    `;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 添加事件监听
screenShareButton.onclick = toggleScreenShare;
sendMessageButton.onclick = sendChatMessage;
chatInput.onkeypress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendChatMessage();
    }
};

// 修改 initWhiteboard 函数
function initWhiteboard() {
    ctx = whiteboardCanvas.getContext('2d');
    
    function resizeCanvas() {
        const container = whiteboardContainer;
        whiteboardCanvas.width = container.clientWidth;
        whiteboardCanvas.height = container.clientHeight;
    }
    
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    // 画笔事件
    whiteboardCanvas.addEventListener('mousedown', startDrawing);
    whiteboardCanvas.addEventListener('mousemove', draw);
    whiteboardCanvas.addEventListener('mouseup', stopDrawing);
    whiteboardCanvas.addEventListener('mouseout', stopDrawing);

    // 触摸事件
    whiteboardCanvas.addEventListener('touchstart', handleTouch);
    whiteboardCanvas.addEventListener('touchmove', handleTouch);
    whiteboardCanvas.addEventListener('touchend', stopDrawing);

    // 工具按钮事件
    penButton.addEventListener('click', () => {
        isErasing = false;
        penButton.classList.add('active');
        eraserButton.classList.remove('active');
        ctx.globalCompositeOperation = 'source-over';
    });

    eraserButton.addEventListener('click', () => {
        isErasing = true;
        eraserButton.classList.add('active');
        penButton.classList.remove('active');
        ctx.globalCompositeOperation = 'destination-out';
    });

    clearButton.addEventListener('click', () => {
        if (confirm('确定要清空白板吗？')) {
            ctx.clearRect(0, 0, whiteboardCanvas.width, whiteboardCanvas.height);
            sendWhiteboardData('clear');
        }
    });

    // 线条粗细控制
    lineWidthControl.addEventListener('input', (e) => {
        currentLineWidth = parseInt(e.target.value);
    });

    // 全屏控制
    fullscreenButton.addEventListener('click', toggleFullscreen);

    // 默认激活画笔
    penButton.click();
}

// 开始绘画
function startDrawing(e) {
    isDrawing = true;
    const pos = getPosition(e);
    lastX = pos.x;
    lastY = pos.y;
}

// 绘画
function draw(e) {
    if (!isDrawing) return;

    const pos = getPosition(e);
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(pos.x, pos.y);
    
    if (isErasing) {
        ctx.strokeStyle = '#000';
        ctx.lineWidth = 20;
    } else {
        ctx.strokeStyle = colorPicker.value;
        ctx.lineWidth = currentLineWidth;
    }
    
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.stroke();
    
    // 发送绘画数据
    sendWhiteboardData('draw', {
        from: { x: lastX, y: lastY },
        to: { x: pos.x, y: pos.y },
        color: colorPicker.value,
        lineWidth: currentLineWidth,
        isErasing: isErasing
    });

    lastX = pos.x;
    lastY = pos.y;
}

// 停止绘画
function stopDrawing() {
    isDrawing = false;
}

// 获取鼠标/触摸位置
function getPosition(e) {
    const rect = whiteboardCanvas.getBoundingClientRect();
    if (e.touches) {
        return {
            x: e.touches[0].clientX - rect.left,
            y: e.touches[0].clientY - rect.top
        };
    }
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

// 处理触摸事件
function handleTouch(e) {
    e.preventDefault();
    const touch = e.type === 'touchstart' ? startDrawing : draw;
    touch(e);
}

// 修改 sendWhiteboardData 函数
function sendWhiteboardData(action, data = null) {
    if (currentCallId) {
        const message = {
            type: 'whiteboard',
            from: userId,
            to: currentCallId,
            data: {
                action: action,
                ...data
            }
        };
        sendMessage(message);
    }
}

// 修改 handleWhiteboardMessage 函数
function handleWhiteboardMessage(message) {
    if (!ctx || message.from === userId) return;

    const data = message.data;
    if (!data || !data.action) return;

    switch (data.action) {
        case 'draw':
            ctx.beginPath();
            ctx.moveTo(data.from.x, data.from.y);
            ctx.lineTo(data.to.x, data.to.y);
            
            if (data.isErasing) {
                ctx.strokeStyle = '#000';
                ctx.lineWidth = 20;
                ctx.globalCompositeOperation = 'destination-out';
            } else {
                ctx.strokeStyle = data.color;
                ctx.lineWidth = data.lineWidth;
                ctx.globalCompositeOperation = 'source-over';
            }
            
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.stroke();
            break;
            
        case 'clear':
            ctx.clearRect(0, 0, whiteboardCanvas.width, whiteboardCanvas.height);
            break;
    }
}

// 添加全屏切换功能
function toggleFullscreen() {
    const videoWrapper = whiteboardContainer.closest('.video-wrapper');
    
    if (!isFullscreen) {
        if (videoWrapper.requestFullscreen) {
            videoWrapper.requestFullscreen();
        } else if (videoWrapper.webkitRequestFullscreen) {
            videoWrapper.webkitRequestFullscreen();
        } else if (videoWrapper.msRequestFullscreen) {
            videoWrapper.msRequestFullscreen();
        }
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

// 监听全屏变化
document.addEventListener('fullscreenchange', handleFullscreenChange);
document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
document.addEventListener('msfullscreenchange', handleFullscreenChange);

function handleFullscreenChange() {
    isFullscreen = !!document.fullscreenElement;
    fullscreenButton.innerHTML = isFullscreen ? 
        '<i class="fas fa-compress"></i>' : 
        '<i class="fas fa-expand"></i>';
    fullscreenButton.title = isFullscreen ? '退出全屏' : '全屏';
} 